﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using API.Models;
using PPG.DataAccess;
using PPG.CryptoProvider;
using System.Xml;
using System.Data;
using System.Configuration;
using System.Web;

namespace API.Controllers
{
    public class UserLogoutController : ApiController
    {
        /// <summary>
        /// Intializing Helper Classes - DB Connection and Security Provider for Encrypting and Decrypting Passwords
        /// Pass in DBServerName, DBUsername and DBPassword from Config File for DB connections
        /// The Security helper does nto take any parameters
        /// </summary>
        DataSourceCommunicator dsComm = new DataSourceCommunicator(DataSourceCommunicator.ParamType.ServerCredentials, ConfigurationManager.AppSettings["DBServerName"].ToString(), ConfigurationManager.AppSettings["DBUserName"].ToString(), ConfigurationManager.AppSettings["DBPassword"].ToString());

        /// <summary>
        /// This function is to post the Logout details of the User
        /// </summary>
        /// 
        [ActionName("UserLogout")]
        public void PostUserLogout(int id)
        {
            //Logging User Action
            dsComm.AddParameter("@ParamLoginID", id);
            dsComm.AddParameter("@ParamActionType", "LO");
            dsComm.AddParameter("@ParamReferenceType", "Audit");
            dsComm.AddParameter("@ParamIPAddress", GetUserIp(Request));
            dsComm.AddParameter("@ParamComment", "Logout");
            dsComm.ExecuteNonQuery("spAddUserAction");
        }

        /// <summary>
        /// Options Resposen for the preflight request of a CORS Opertaions. Will be standard across various functions
        /// </summary>
        /// <returns></returns>
        public HttpResponseMessage OptionsUserLogout()
        {
            var response = new HttpResponseMessage();
            response.StatusCode = HttpStatusCode.OK;
            return response;
        }

        //Used to find the RequestIP
        public string GetUserIp(HttpRequestMessage request)
        {
            if (request.Properties.ContainsKey("MS_HttpContext"))
            {
                var ctx = request.Properties["MS_HttpContext"] as HttpContextBase;
                if (ctx != null)
                {
                    return ctx.Request.UserHostAddress;
                }
            }

            return null;
        }
    }
}
